<?php 
	require_once("MoneyFactory.class.php"); 
	require_once("PorteMonnaie.class.php");

	if(isset($_POST['m2']) && isset($_POST['c2'])) {
		
		$m2 = MoneyFactory::getDefaultFactory()->createMoney($_POST['m2'],"EUR");
	}
	else{

			$m2 = MoneyFactory::getDefaultFactory()->createMoney(0,"EUR");
			echo "<div id='result'>Votre porte monnaie contient : <br/>";

			echo "(EUR) 0 <br/> </div>";


	}

	function processRequest($request) {
		global $m2;
		global $c2;

		if (isset($request["ops"]) && isset($request["v1"]) && isset($request["c1"]))
		{
			$m1=MoneyFactory::getDefaultFactory()->createMoney($request["v1"],$request["c1"]);
			
			$opsCode=$request["ops"];

			echo $request["c1"];
			echo "<div id='result'>Votre porte monnaie contient : </div>";
			echo "<div id='result_detail'>";

			try{
				if (strcmp($opsCode,"ADD")==0) {

					$res=PorteMonnaie::add($m1,$m2);
				}
				if (strcmp($opsCode,"REM")==0) {
					$res=PorteMonnaie::suppr($m2,$m1);
				}
			} 
			catch (NotEnoughMoneyException $e){
				echo "<script language=\"javascript\">
alert(\"Operation impossible, vous n'avez pas assez d'argent\")
</script>";
				$res=$m2;}				
			
			if (isset($res) && ($res instanceOf Money)) {
				echo "(",$res->getCurrency(),") ",$res->getValue();
			} 
			else echo "Unsupported operations"; 
			
			$c2 = $request["c1"];

			$m2 = $res;
			echo "</div>";
			
		}
	
	}
?>
<html>
	<head>
		<title>Money Operations</title>
		<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
	</head>
	<body>
		<?php
		processRequest($_REQUEST);	
		?>
		<hr width='20%' align='left'/>
		<form action='index.php' method='post' id='form0'>
			<input type='hidden' id='m2' name='m2' value='<?php echo $m2->getValue();?>'/>
			<input type='hidden' id='c2' name='c2' value='<?php echo $c2; ?>'/>
			
		<table>
			<tr>
			  <td>Valeur</td><td>Devise</td><td>Opération</td>
			</tr>
			<tr>
			  <td><input type='text' id='v1' name='v1' value='<?php echo $_REQUEST["v1"];?>'/></td>
			   <td><input type='text' id='c1' name='c1' value='<?php echo $_REQUEST["c1"];?>'/></td>
			  <td><select name='ops'><option value='ADD'>+</option><option value='REM'>-</option></select></td>
			</tr>
			<tr>
			   <td colspan='5' align='right'><input type='submit' value='calculer'/></td>			
			</tr>
		</table>
		</form>
	</body>
</html>
